import { shell, BrowserWindow } from 'electron'
import { is } from '@electron-toolkit/utils'

import { join } from 'path'

export default {
  createWindow(options?): void {
    // Create the browser window.
    const defaultOptions = {
      width: 900,
      height: 670,
      show: false,
      autoHideMenuBar: true,
      webPreferences: {
        preload: join(__dirname, '../preload/index.js'),
        sandbox: false
      }
    }
    const mainWindow = new BrowserWindow(Object.assign({}, defaultOptions, options))

    mainWindow.on('ready-to-show', () => {
      mainWindow.show()
    })

    mainWindow.webContents.setWindowOpenHandler((details) => {
      shell.openExternal(details.url)
      return { action: 'deny' }
    })

    if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
      mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
    } else {
      mainWindow.loadFile(join(__dirname, '../renderer/src/index.html'))
    }
  },
  createChildWindow(url: string, options): void {
    // Create the browser window.
    const defaultOptions = {
      width: 600,
      height: 400,
      show: false,
      autoHideMenuBar: true,
      webPreferences: {
        preload: join(__dirname, '../preload/index.js'),
        sandbox: false
      }
    }
    const mainWindow = new BrowserWindow(Object.assign({}, defaultOptions, options))

    mainWindow.on('ready-to-show', () => {
      mainWindow.show()
    })

    mainWindow.webContents.setWindowOpenHandler((details) => {
      shell.openExternal(details.url)
      return { action: 'deny' }
    })

    // HMR for renderer base on electron-vite cli.
    // Load the remote URL for development or the local html file for production.
    if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
      console.log('子窗口加载', url)
      mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'] + '/chatHistory')
    } else {
      mainWindow.loadFile(join(__dirname, '../renderer/src/index.html'))
    }
  }
}
